//
//  VideoDetailViewController.m
//  DMT_VR
//
//  Created by xin on 16/10/18.
//  Copyright © 2016年 Elephant-Parade. All rights reserved.
//

#import "VideoDetailViewController.h"
#import "DMTMD360PlayViewController.h"
#import "VedioModel.h"

#import <ReactiveObjC/ReactiveObjC.h>
#import <AFNetworking/AFNetworking.h>
#import "Masonry.h"
#import "MBProgressHUD.h"
#import "UIImageView+YYWebImage.h"
#import "HSDownloadManager.h"

#define WHC_BackgroundDownload (0)

@interface VideoDetailViewController ()

@property (strong, nonatomic) UIScrollView * scrollView;
@property (strong, nonatomic) UIImageView *detailImageView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UIButton *playButton;
@property (strong, nonatomic) UILabel *titleLabel;
@property (strong, nonatomic) UILabel *infoLabel;
@property (strong, nonatomic) UITextView *infoTextView;
@property (strong, nonatomic) UIButton *shareButton;
@property (strong, nonatomic) UIButton *downloadButton;
@property (strong, nonatomic) UILabel * currentDownloadLabel;

@property (nonatomic,strong) NSString *localPath;
@property (nonatomic,strong) NSString *onlineM3U8;
@property (nonatomic,strong) NSString *onlineMP4;
@property (nonatomic,strong) NSArray *dataSource;

- (void)launchAsVideo;

@end

@implementation VideoDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //判断当前视频本地是否缓存过
    //    for(VedioModel * model in [FileDownloadManager sharedInstance].finishTaskArray){
    //        if(model.vedioid == self.vedioModel.vedioid && model.cacheType != 0)
    //        {
    //            self.vedioModel = model;
    //        }
    //        NSLog(@"lacationurl=%@",self.vedioModel.filepath);
    //    }
    
    //UI布局
    self.view.backgroundColor = [UIColor colorWithRed:35/255.f green:37/255.f blue:39/255.f alpha:1];
    
    _detailImageView = [UIImageView new];
    _detailImageView.clipsToBounds = YES;
    _detailImageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:_detailImageView];
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"btn_detail_back"] forState:UIControlStateNormal];
    [self.view addSubview:_backButton];
    
    _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton setImage:[UIImage imageNamed:@"btn_detail_play"] forState:UIControlStateNormal];
    [self.view addSubview:_playButton];
    
    _titleLabel = [UILabel new];
    _titleLabel.textColor = [UIColor whiteColor];
    _titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:18];
    [self.view addSubview:_titleLabel];
    
    _infoLabel = [UILabel new];
    _infoLabel.textColor = [UIColor whiteColor];
    _infoLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
    [self.view addSubview:_infoLabel];
    
    _currentDownloadLabel = [UILabel new];
    _currentDownloadLabel.textColor = [UIColor whiteColor];
    _currentDownloadLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
    [self.view addSubview:_currentDownloadLabel];
    
    _infoTextView = [UITextView new];
    _infoTextView.textColor = [UIColor whiteColor];
    _infoTextView.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    _infoTextView.editable = NO;
    _infoTextView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_infoTextView];
    
    _shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareButton setImage:[UIImage imageNamed:@"btn_detail_share"] forState:UIControlStateNormal];
    [_shareButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _shareButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    _shareButton.titleEdgeInsets = UIEdgeInsetsMake(0, 20, 0, 0);
    [self.view addSubview:_shareButton];
    
    _downloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _downloadButton.backgroundColor = [UIColor clearColor];
    [_downloadButton setImage:[UIImage imageNamed:@"btn_detail_download"] forState:UIControlStateNormal];
    
    [_downloadButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_downloadButton setTitleColor:[UIColor grayColor] forState:UIControlStateDisabled];
    _downloadButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Medium" size:14];
    _downloadButton.titleEdgeInsets = UIEdgeInsetsMake(0, 8, 0, 0);
    [self.view addSubview:_downloadButton];
    
    [_detailImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@0);
        make.left.equalTo(@0);
        make.right.equalTo(@0);
        make.width.equalTo(self.view.mas_width);
        make.height.equalTo(self.view.mas_width);
    }];
    
    [_backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(@50);
        make.height.equalTo(@50);
        make.left.equalTo(@0);
        make.top.equalTo(@20);
    }];
    
    [_playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(_detailImageView);
    }];
    
    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@16);
        make.top.equalTo(_detailImageView.mas_bottom).with.offset(16);
        make.right.equalTo(@(-16));
    }];
    
    [_infoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel);
        make.top.equalTo(_titleLabel.mas_bottom);
        make.right.equalTo(_titleLabel);
    }];
    
    [_infoTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_titleLabel);
        make.top.equalTo(_infoLabel.mas_bottom).with.offset(8);
        make.right.equalTo(_titleLabel);
        make.height.greaterThanOrEqualTo(@60);
    }];
    
    [_downloadButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@0);
        make.top.equalTo(_infoTextView.mas_bottom).with.offset(8);
        make.bottom.equalTo(@(0));
        make.width.equalTo(@100);
        make.height.equalTo(@44);
    }];
    
    [_shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(_downloadButton);
        make.width.equalTo(_downloadButton);
        make.right.equalTo(_downloadButton.mas_left).with.offset(0);
    }];
    
    [_currentDownloadLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
    }];
    
    [[self.backButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [[self.playButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        [self launchAsVideo];
    }];
    
    @weakify(self);
    [[self.downloadButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        @strongify(self);
        //保存model到本地plist
        [VedioModel saveCache:self.vedioModel];
        //创建下载
        [[HSDownloadManager sharedInstance] download:self.vedioModel.vediourl progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString * value = [NSString stringWithFormat:@"%.f%%",progress * 100];
                if (progress == 0.0) {
                    value = @"缓存";
                }
                
                [self.downloadButton setTitle:value forState:UIControlStateNormal];
            });
        } state:^(DownloadState state) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (state == DownloadStateCompleted) {
                    self.downloadButton.enabled = NO;
                    [self.downloadButton setTitle:@"已缓存" forState:UIControlStateNormal];
                }
            });
        }];
        
    }];
    
    self.shareButton.hidden = YES;
    [[self.shareButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
    }];
    
    self.infoTextView.text = _vedioModel.info;
    self.titleLabel.text = [NSString stringWithFormat:@"%@ %@",_vedioModel.title_ch,_vedioModel.title_en];
    self.infoLabel.text = [NSString stringWithFormat:@"#%@ / %@",_vedioModel.type,_vedioModel.vediotime];
    NSURL * imagePath = [NSURL URLWithString:_vedioModel.imgurl];
    [self.detailImageView
     setImageWithURL:imagePath
     placeholder:[UIImage imageNamed:@"placeholder"]
     options:YYWebImageOptionSetImageWithFadeAnimation
     completion:^(UIImage * _Nullable image, NSURL * _Nonnull url, YYWebImageFromType from, YYWebImageStage stage, NSError * _Nullable error) {
         
     }];
    
    
    //再次进入该页面时监听当前url是否下载完成
    [[HSDownloadManager sharedInstance] wxDownload:self.vedioModel.vediourl progress:^(NSInteger receivedSize, NSInteger expectedSize, CGFloat progress) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString * value = [NSString stringWithFormat:@"%.f%%",progress * 100];
            if (progress-1.0 == 0) {
                value = @"已缓存";
            }
            else if(progress == 0.0)
            {
                value = @"";
            }
            
            [self.downloadButton setTitle:value forState:UIControlStateNormal];
        });
    } state:^(DownloadState state) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (state == DownloadStateCompleted) {
                self.downloadButton.enabled = NO;
                [self.downloadButton setTitle:@"已缓存" forState:UIControlStateNormal];
            }
        });
    }];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBar.hidden = YES;
    
}

- (void)launchAsVideo {
    
        NSURL * url;
        if ([[HSDownloadManager sharedInstance] isCompletion:self.vedioModel.vediourl]) {
            
            NSString *path = [[HSDownloadManager sharedInstance] completionFilePath:self.vedioModel.vediourl];
    
            url = [NSURL fileURLWithPath:path];
    
            NSLog(@"本地视频=%@",url);
        }
        else{
            url = [NSURL URLWithString:_vedioModel.vediourl];
            NSLog(@"网络视频=%@",url);
        }
    
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"DMTMD360PlayViewController" bundle:nil];
        DMTMD360PlayViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"DMTMD360PlayViewController"];
        [self presentViewController:vc animated:YES completion:^{
            [vc initParams:url title:_vedioModel.title_ch];
        }];
    
}

#pragma mark - 屏幕方向
- (BOOL)shouldAutorotate{
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}
#pragma mark - 状态栏
//设置样式
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

//设置是否隐藏
- (BOOL)prefersStatusBarHidden {
    //    [super prefersStatusBarHidden];
    return NO;
}

//设置隐藏动画
- (UIStatusBarAnimation)preferredStatusBarUpdateAnimation {
    return UIStatusBarAnimationNone;
}
@end
